/**
 * FileName:     TransactionManager.java
 * CreationTime: 2010-5-2
 * Author:       季乐
 * EMail:        keydot@msn.com
 * CopyRight: 2010-2012 All Recieves.
 */
package org.shock.ss.sms.commons.db;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

/**
 * 事务管理器
 * 
 * @author 季乐
 */
public class TransactionManager {
	private Connection conn;
	private Logger log = Logger.getLogger(getClass());

	protected TransactionManager(Connection conn) {
		if (conn == null) {
			throw new RuntimeException("数据库连接失败！");
		}
		this.conn = conn;
	}

	public TransactionManager() {
		super();
	}

	/**
	 * 开启事务
	 * 
	 * @throws SQLException
	 */
	public void beginTransaction() throws SQLException {
		try {
			conn.setAutoCommit(false); // 把事务提交方式改为手工提交
			log.debug("开启事务");
		} catch (SQLException e) {
			log.debug(e, e);
			throw e;
		}
	}

	/**
	 * 提交事务并关闭连接
	 * 
	 * @throws SQLException
	 */
	public void commitAndClose() throws SQLException {
		try {
			conn.commit(); // 提交事务
			log.debug("提交事务");
		} catch (SQLException e) {
			throw e;
		} finally {
			ProxoolDbPool.closeConnection(conn);
		}
	}

	/**
	 * 回滚并关闭连接
	 * 
	 * @throws Exception
	 */
	public void rollbackAndClose() throws Exception {
		try {
			if (!conn.isClosed()) {
				conn.rollback();
				log.warn("====事务回滚====");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.debug(e, e);
			throw e;
		} finally {
			ProxoolDbPool.closeConnection(conn);
		}
	}
}
